package com.example.demo.jpa.config.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    Logger logger = LoggerFactory.getLogger(CustomResponseEntityExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(CustomException.class)
    public ResponseEntity<MyErrorBody> handleControllerException(HttpServletRequest request, CustomException ex) {
        logger.error("",ex);
        ExceptionResp resp = ex.getExceptionResp();
        return new ResponseEntity<>(new MyErrorBody(resp.getCode(), ex.getMsg()), HttpStatusCode.valueOf(resp.getStatus()));
    }


    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<MyErrorBody> runtimeException(HttpServletRequest request, RuntimeException ex) {
        logger.error("",ex);
        ExceptionResp resp = ExceptionResp.INTERNAL_ERROR;
        return new ResponseEntity<>(new MyErrorBody(resp.getCode(), ex.getMessage()), HttpStatusCode.valueOf(resp.getStatus()));
    }
}
